import message from "./message";

export const getVideoSize = (file: any) => {
  return new Promise<{ w: number; h: number; d: number } | false>(
    (reslove, reject) => {
      try {
        if (!file) {
          message.warning("请选择上传视频");
          reslove(false);
        }
        var video = document.createElement("video");
        video.addEventListener("loadedmetadata", function () {
          reslove({
            w: video.videoWidth,
            h: video.videoHeight,
            d: video.duration
          });
        });
        if (typeof file === "string") {
          video.src = file;
        } else {
          video.src = URL.createObjectURL(file);
        }
      } catch (error: any) {
        message.warning(error);
        reslove(false);
      }
    }
  );
};

export const sliceVideo = (
  videoFile: File,
  chunkSize: number,
  callback: (
    chunk: File,
    chunkIndex: number,
    start: number,
    end: number
  ) => void
) => {
  const blobSlice =
    File.prototype.slice ||
    File.prototype.webkitSlice ||
    File.prototype.mozSlice;
  let chunks = Math.ceil(videoFile.size / chunkSize);
  let currentChunk = 0;

  const loadNextChunk = () => {
    if (currentChunk < chunks) {
      let start = currentChunk * chunkSize;
      let end = Math.min(videoFile.size, start + chunkSize);
      let chunk = blobSlice.call(videoFile, start, end);
      let resFile = new File([chunk], `chunk_${currentChunk}.mp4`);
      callback(resFile, currentChunk++, start, end);
      loadNextChunk();
    }
  };

  loadNextChunk();
};
